from Bases import BaseObject
from baseview import BaseView
from .. import editors
from ..bases import widgets

class PaletteView(BaseView):
    _view_name = 'Palettes'
    def init_view(self, **kwargs):
        self.topwidget = widgets.Frame(label='Palettes', label_kwargs={'size_hint_y':.05})
        #vbox = widgets.VBox(size_hint_y=.1)
        self.add_editor(GroupSelect, 'group_select')
        #vbox.add_widget(self.group_select.topwidget)
        self.topwidget.add_widget(self.group_select.topwidget)
        self.group_select.bind(current_group=self.on_current_group)
        
        table = widgets.Table(cols=2)
        for key, val in self.MainController.EffectsSystem.CategoryPalettes.iteritems():
            grid = self.add_editor(PaletteGrid, '_'.join([key, 'grid']), 
                                   PaletteGroup=val, group_select=self.group_select)
            table.add_widget(grid.topwidget)
        self.topwidget.add_widget(table)
        
    def on_current_group(self, **kwargs):
        pass
        
        
class GroupSelect(editors.EditorBase):
    topwidget_label = 'Select Group'
    _Properties = {'current_group':dict(ignore_type=True, quiet=True)}
    def init_editor(self, **kwargs):
        #self.topwidget = widgets.HBox()
        
        self.table = widgets.Table(cols=16, size_hint_y=.75)
        self.btns = {}
        for key, val in self.MainController.Groups.indexed_items.iteritems():
            toggle = GroupSelectBtn(label=val.name, group=val, index=key)
            #toggle.Property = (toggle, 'selected')
            toggle.bind(state=self.on_group_selected)
            self.btns[key] = toggle
            self.table.add_widget(toggle.widget)
        self.topwidget.add_widget(self.table)
        self.topwidget.size_hint_y = .2
    def on_group_selected(self, **kwargs):
        toggle = kwargs.get('obj')
        state = kwargs.get('value')
        if state:
            self.current_group = toggle.group
            for w in self.btns.itervalues():
                if w.index != toggle.index:
                    w.state = False
            
class GroupSelectBtn(widgets.ToggleBtn):
    #_Properties = {'selected':dict(default=False, quiet=True)}
    def __init__(self, **kwargs):
        self.group = kwargs.get('group')
        self.index = kwargs.get('index')
        super(GroupSelectBtn, self).__init__(**kwargs)

class PaletteGrid(editors.EditorBase):
    topwidget_label = 'Palette'
    def init_editor(self, **kwargs):
        self.current_group = None
        self.group_select = kwargs.get('group_select')
        self.PaletteGroup= kwargs.get('PaletteGroup')
        self.topwidget.set_label(self.PaletteGroup.name)
        self.toggles = {}
        self.table = widgets.Table(cols=6)
        for key, val in self.PaletteGroup.indexed_items.iteritems():
            toggle = PaletteBtn(Palette=val, parent=self)
            self.toggles[key] = toggle
            self.table.add_widget(toggle.widget)
        self.topwidget.add_widget(self.table)
        self.group_select.bind(current_group=self.on_current_group_set)
    
    def unlink(self):
        super(PaletteGrid, self).unlink()
        self.group_select.unbind(self)
        if self.current_group is not None:
            self.current_group.unbind(self)
        
    @property
    def category(self):
        return self.PaletteGroup.category.name
        
    def on_current_group_set(self, **kwargs):
        #old = kwargs.get('old')
        #group = kwargs.get('value')
        if self.current_group is not None:
            self.current_group.unbind(self.on_group_ActivePalettes_changed)
        if self.category == 'Color':
            self.LOG.info('group set: ', kwargs)
        #for btn in self.palette_buttons.itervalues():
        #    btn.on_current_group_set(**kwargs)
        self.current_group = self.group_select.current_group
        if self.current_group is not None:
            self.current_group.bind(ActivePalettes=self.on_group_ActivePalettes_changed)
            value = self.current_group.ActivePalettes
        else:
            value = {self.category:0}
        self.on_group_ActivePalettes_changed(value=value)
        
    def on_group_ActivePalettes_changed(self, **kwargs):
        old = kwargs.get('old', {})
        value = kwargs.get('value', {})
        group = kwargs.get('obj')
        if group != self.current_group:
            return
        if self.category == 'Color':
            self.LOG.info('AP change: ', self.category, old, value)
        if old.get(self.category) == value.get(self.category):
            return
        for btn in self.toggles.itervalues():
            btn.on_group_ActivePalettes_changed(**kwargs)
        
class PaletteBtn(BaseObject):
    _Properties = {'active':dict(default=False)}
    def __init__(self, **kwargs):
        self.Palette = kwargs.get('Palette')
        self.parent = kwargs.get('parent')
        super(PaletteBtn, self).__init__(**kwargs)
        self.widget = widgets.Button(label=self.Palette.name)
        self.widget.bind(on_release=self.on_widget_release)
        #self.Index = self.palette.Index
        #self.Property = (self, 'toggle_active')
        #self.palette.bind(active=self.on_palette_active_set)
        self.bind(active=self._on_active_set)
        #self.parent.group_select.bind(current_group=self.on_current_group_set)
    @property
    def _Index(self):
        return self.Palette.Index
    @property
    def current_group(self):
        return self.parent.group_select.current_group
    @property
    def category(self):
        return self.Palette.category.name
    @property
    def palette_is_active(self):
        if self.current_group is None:
            return False
        return self.current_group.ActivePalettes.get(self.category) == self._Index
    
    def on_widget_release(self, *args):
        if not self.current_group:
            self.active = False
            return
        if self.palette_is_active:
            self.current_group.del_active_palette(category=self.category)
        else:
            self.Palette.set_groups(group=self.current_group)
        self.active = self.palette_is_active
        
    def _on_active_set(self, **kwargs):
        state = self.active
        if self.widget.bool_state != state:
            self.widget.bool_state = state
        
#    def on_current_group_set(self, **kwargs):
#        old = kwargs.get('old')
#        group = kwargs.get('value')
#        if old is not None:
#            old.unbind(self)
#        if group is not None:
#            group.bind(ActivePalettes=self.on_group_ActivePalettes_changed)
#        self.on_group_ActivePalettes_changed()
        
    def on_group_ActivePalettes_changed(self, **kwargs):
        #if self.category == 'Color' and self._Index < 4:
        #    print '%s AP change: ' % (self._Index), kwargs
        if self.active != self.palette_is_active:
            self.active = self.palette_is_active
